package com.isman.placeslist;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.isman.placeslist.apiobject.Status;
import com.isman.placeslist.apiobject.Status.Location;
import com.isman.placeslist.util.GeoLocation;
import com.isman.placeslist.util.GeoLocation.LocationResult;
import com.isman.placeslist.util.Util;
import com.isman.placeslist.ws.AsyncRunnerHeadler;
import com.isman.placeslist.ws.ServiceProvider;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.TabHost.TabSpec;
import android.widget.Toast;

public class PageSearchSort extends Activity {
	public static final String FROM = "from";
	public static final int FROM_NOMAL = 0;
	public static final int FROM_NEWSTATUS = 1;
	private int mFrom;

	private ListView ls1;
	private ListView ls2;
	private ListView ls3;
	private ListView ls4;
	private TabHost myTabHost;

	@Override
	public void onCreate(Bundle icicle) {

		super.onCreate(icicle);
		setContentView(R.layout.page_search_sort);
		mFrom = getIntent().getIntExtra(FROM, FROM_NOMAL);

		init();
		initData();
		mFooter();
		mGetLocation();
	}

	protected void init() {
		this.myTabHost = (TabHost) this.findViewById(R.id.tabhost);
		this.myTabHost.setup();
		ls1 = new ListView(this);
		ls2 = new ListView(this);
		ls3 = new ListView(this);
		ls4 = new ListView(this);

		addTabHotel();
		addTabShop();
		addTabRestaurant();
		addTabTravel();

		vedtInput = (EditText) findViewById(R.id.edt_search_sort_input);
		vibtnGo = (ImageButton) findViewById(R.id.ibtn_search_sort_go);
		vibtnGo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mSearch();
			}
		});
	}

	protected void initData() {
		mSearch();
	}

	protected void mFooter() {
		View view = LayoutInflater.from(this).inflate(
				R.layout.inc_item_newplace, null);
		view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				startActivity(new Intent(PageSearchSort.this,
						PageNewPlace.class));
			}
		});
		ls1.addFooterView(view);
		ls2.addFooterView(view);
		ls3.addFooterView(view);
		ls4.addFooterView(view);
	}

	protected void mSearch() {
		String str = vedtInput.getText().toString().trim().equals("") ? "null"
				: vedtInput.getText().toString().trim();
		ServiceProvider provider = new ServiceProvider(this);
		provider.SearchPlace(mLongitude, mLatitude, str,
				new AsyncRunnerHeadler() {

					@Override
					public void onError(int statusCode, String json) {
					}

					@Override
					public void onConnectingError(String message) {
					}

					@Override
					public void onComplete(String json) {
						Log.e("TAG", json);

						Type type = new TypeToken<ArrayList<Location>[]>() {
						}.getType();
						mLocation = new Gson().fromJson(json, type);

						adapter1 = new LocationAdapter(PageSearchSort.this,
								mLocation[2], mFrom);
						adapter2 = new LocationAdapter(PageSearchSort.this,
								mLocation[3], mFrom);
						adapter3 = new LocationAdapter(PageSearchSort.this,
								mLocation[0], mFrom);
						adapter4 = new LocationAdapter(PageSearchSort.this,
								mLocation[1], mFrom);
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								ls1.setAdapter(adapter1);
								ls2.setAdapter(adapter2);
								ls3.setAdapter(adapter3);
								ls4.setAdapter(adapter4);
							}
						});
					}

					@Override
					public void onAuthenticate(String json) {
					}
				});
	}

	protected void mGetLocation() {
		GeoLocation geoLocation = new GeoLocation();
		geoLocation.getLocation(this, new LocationResult() {
			@Override
			public void gotLocation(android.location.Location location) {
				if (location != null) {
					mLatitude = location.getLatitude();
					mLongitude = location.getLongitude();
					Log.i("Latitude", location.getLatitude()+"");
					Log.i("Longitude", location.getLongitude()+"");
					mSearch();
				}
			}
		});
	}

	private void addTabTravel() {
		TabHost.TabSpec spec = myTabHost.newTabSpec("Travel");
		View tabIndicator = LayoutInflater.from(this).inflate(
				R.layout.inc_tab_indicator_search, myTabHost.getTabWidget(),
				false);
		tabIndicator.setBackgroundResource(R.drawable.bg_tab_indicator_right);
		TextView title = (TextView) tabIndicator.findViewById(R.id.title);
		title.setText("Travel");

		spec.setIndicator(tabIndicator);
		spec.setContent(new TabHost.TabContentFactory() {
			public View createTabContent(String tag) {
				return ls4;
			}
		});
		myTabHost.addTab(spec);
	}

	private void addTabShop() {
		TabHost.TabSpec spec = myTabHost.newTabSpec("Shop");
		View tabIndicator = LayoutInflater.from(this).inflate(
				R.layout.inc_tab_indicator_search, myTabHost.getTabWidget(),
				false);
		tabIndicator.setBackgroundResource(R.drawable.bg_tab_indicator_center);
		TextView title = (TextView) tabIndicator.findViewById(R.id.title);
		title.setText("Shop");

		spec.setIndicator(tabIndicator);
		spec.setContent(new TabHost.TabContentFactory() {
			public View createTabContent(String tag) {
				return ls2;
			}
		});
		myTabHost.addTab(spec);
	}

	private void addTabRestaurant() {
		TabHost.TabSpec spec = myTabHost.newTabSpec("Restaurant");
		View tabIndicator = LayoutInflater.from(this).inflate(
				R.layout.inc_tab_indicator_search, myTabHost.getTabWidget(),
				false);
		tabIndicator.setBackgroundResource(R.drawable.bg_tab_indicator_center);
		TextView title = (TextView) tabIndicator.findViewById(R.id.title);
		title.setText("Restaurant");

		spec.setIndicator(tabIndicator);
		spec.setContent(new TabHost.TabContentFactory() {
			public View createTabContent(String tag) {
				return ls3;
			}
		});
		myTabHost.addTab(spec);
	}

	private void addTabHotel() {
		TabHost.TabSpec spec = myTabHost.newTabSpec("Hotel");
		View tabIndicator = LayoutInflater.from(this).inflate(
				R.layout.inc_tab_indicator_search, myTabHost.getTabWidget(),
				false);
		tabIndicator.setBackgroundResource(R.drawable.bg_tab_indicator_left);
		TextView title = (TextView) tabIndicator.findViewById(R.id.title);
		title.setText("Hotel");

		spec.setIndicator(tabIndicator);
		spec.setContent(new TabHost.TabContentFactory() {
			public View createTabContent(String tag) {
				return ls1;
			}
		});
		myTabHost.addTab(spec);
	}

	private ImageButton vibtnGo;
	private EditText vedtInput;

	private ArrayList<Location>[] mLocation;
	private double mLatitude = 0;
	private double mLongitude = 0;

	private LocationAdapter adapter1;
	private LocationAdapter adapter2;
	private LocationAdapter adapter3;
	private LocationAdapter adapter4;

	public static class LocationAdapter extends BaseAdapter {
		private ArrayList<Location> mLocations = new ArrayList<Status.Location>();
		private Activity mActivity;
		private int mFrom;

		public LocationAdapter(Activity mActivity,
				ArrayList<Location> mLocations, int mFrom) {
			this.mActivity = mActivity;
			this.mLocations.addAll(mLocations);
			this.mFrom = mFrom;
		}

		@Override
		public int getCount() {
			return this.mLocations.size();
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			final Location lo = mLocations.get(arg0);

			View view = LayoutInflater.from(mActivity).inflate(
					R.layout.inc_item_place_item_medium, null);
			TextView txtName = (TextView) view
					.findViewById(R.id.lbl_item_pl_name);
			TextView txtCheckCount = (TextView) view
					.findViewById(R.id.lbl_item_pl_checkinCount);
			TextView txtPlace = (TextView) view
					.findViewById(R.id.lbl_item_pl_place);
			ImageView imgLogo = (ImageView) view
					.findViewById(R.id.img_item_pl_logo);

			StringBuilder sb = new StringBuilder();
			if (lo.getMap() != null) {
				if (lo.getMap().getSubLocality() != null) {
					sb.append(lo.getMap().getSubLocality() + " ");
				}
				if (lo.getMap().getLocality() != null) {
					sb.append(lo.getMap().getLocality() + " ");
				}
				if (lo.getMap().getAdminArea() != null) {
					sb.append(lo.getMap().getAdminArea() + " ");
				}
				if (lo.getMap().getCountryName() != null) {
					sb.append("\n" + lo.getMap().getCountryName() + " ");
				}
				if (lo.getMap().getCountryCode() != null) {
					sb.append(lo.getMap().getCountryCode());
				}
			}
			txtName.setText(lo.getName());
			Util.getBitmap(lo.getPicture(), mActivity, imgLogo);
			txtPlace.setText(sb);
			txtCheckCount.setText(lo.getCheckInCount() + "");

			view.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (mFrom == 0) {
						Intent intent = new Intent(mActivity, PagePlace.class);
						intent.putExtra(PagePlace.LOCATION_ID, lo.getId());
						mActivity.startActivity(intent);
					} else {
						Intent intent = new Intent();
						intent.putExtra(PageNewStatus.LOCATION_INFO, lo);
						mActivity.setResult(Activity.RESULT_OK, intent);
					}
				}
			});
			return view;
		}

	}
}
